#!/bin/bash

### full version (not on login, otherwise you can't log when OpenGL/Vulkan are out of order)
if test "$1" = "--full"; then
	FULL_DISPLAY=1
else
	FULL_DISPLAY=0
fi
###

if test -z "${DISPLAY}"; then
    export DISPLAY=$(getLocalXDisplay)
fi

getCpu() {
    test -e "${1}/cpufreq/scaling_max_freq" || return 0

    if test -e "${1}/online"; then
        OL=$(cat "${CPU}/online")
        test "${OL}" = 1 || return 0
    fi
    cat "${CPU}/cpufreq/scaling_max_freq"
}

# Detect battery
BATTERY_DIR=$(ls -d /sys/class/power_supply/*{BAT,bat}* 2>/dev/null | head -1)
BATT=$(cat ${BATTERY_DIR}/uevent 2>/dev/null | grep -E "^POWER_SUPPLY_CAPACITY=" | sed -e s+'^POWER_SUPPLY_CAPACITY='++ | sort -rn | head -1)

if [ -z "${BATT}" ]; then
    BATTERY_DIR=$(ls -d /sys/class/power_supply/*{FUEL,fuel}* 2>/dev/null | head -1)
    NOW=$(cat ${BATTERY_DIR}/uevent 2>/dev/null | grep -E "^POWER_SUPPLY_CHARGE_NOW=" | sed -e s+'^POWER_SUPPLY_CHARGE_NOW='++ | sort -rn | head -1)
    MAX=$(cat ${BATTERY_DIR}/uevent 2>/dev/null | grep -E "^POWER_SUPPLY_CHARGE_FULL=" | sed -e s+'^POWER_SUPPLY_CHARGE_FULL='++ | sort -rn | head -1)
    if [ -n "$NOW" ] && [ -n "$MAX" ] && [ "$MAX" -ne 0 ]; then
        BATT=$((200 * $NOW / $MAX % 2 + 100 * $NOW / $MAX))
    fi
fi

if [ -n "${BATTERY_DIR}" ]; then
    BATTREMAINING=""
    TIME_TO_EMPTY=$(cat ${BATTERY_DIR}/uevent 2>/dev/null | grep -E "^POWER_SUPPLY_TIME_TO_EMPTY_NOW=" | sed -e 's/^POWER_SUPPLY_TIME_TO_EMPTY_NOW=//')

    if [ -n "${TIME_TO_EMPTY}" ] && [ "${TIME_TO_EMPTY}" -gt 0 ]; then
        BATTREMAINING_HOURS=$(expr ${TIME_TO_EMPTY} / 3600)
        BATTREMAINING_MINS=$(expr ${TIME_TO_EMPTY} % 3600 / 60)
        [ ${BATTREMAINING_MINS} -lt 10 ] && BATTREMAINING_MINS=0${BATTREMAINING_MINS}
        BATTREMAINING=" (${BATTREMAINING_HOURS}:${BATTREMAINING_MINS})"
    else
        BATTREMAINING_CURRENT=$(cat ${BATTERY_DIR}/current_now 2>/dev/null)
        BATTREMAINING_CHARGE=$(cat ${BATTERY_DIR}/charge_now 2>/dev/null)
        if [ -n "${BATTREMAINING_CURRENT}" ] && [ -n "${BATTREMAINING_CHARGE}" ]; then
            if [ "${BATTREMAINING_CURRENT}" -gt 0 ]; then
                TIME_TO_EMPTY=$(expr ${BATTREMAINING_CHARGE} \* 3600 / ${BATTREMAINING_CURRENT})
                BATTREMAINING_HOURS=$(expr ${TIME_TO_EMPTY} / 3600)
                BATTREMAINING_MINS=$(expr ${TIME_TO_EMPTY} % 3600 / 60)
                [ ${BATTREMAINING_MINS} -lt 10 ] && BATTREMAINING_MINS=0${BATTREMAINING_MINS}
                BATTREMAINING=" (${BATTREMAINING_HOURS}:${BATTREMAINING_MINS})"
            fi
        fi
    fi
fi	

### short version (for osd)
if test "$1" = "--short"; then
    DT=$(date +%H:%M)
    if test -n "${BATT}"; then
        echo "Battery: ${BATT}%${BATTREMAINING} - ${DT}"
    else
        echo "${DT}"
    fi
    exit 0
fi
###

V_BOARD=$(cat /boot/boot/batocera.board)
V_CPUNB=$(LC_ALL=C lscpu | grep 'Core(s) per socket' | awk '{print $4}' | head -n 1)
V_CPUMAXNB=$(LC_ALL=C lscpu | grep '^CPU(s):' | awk '{print $2}')
V_CPUMODEL1=$(grep -E $'^model name\t:' /proc/cpuinfo | head -1 | sed -e s+'^model name\t: '++)
V_SYSTEM=$(uname -rs)
# min freq : minimum freq among the max cpus ; consider only online cpus
V_CPUMINFREQ=$(for CPU in /sys/devices/system/cpu/cpu*; do getCpu "${CPU}"; done | sort -n  | head -1)
V_CPUMAXFREQ=$(for CPU in /sys/devices/system/cpu/cpu*; do getCpu "${CPU}"; done | sort -rn | head -1)
let V_CPUMINFREQ=${V_CPUMINFREQ}/1000
let V_CPUMAXFREQ=${V_CPUMAXFREQ}/1000

V_BOARD_MODEL=$(batocera-model)
if test -n "${V_BOARD_MODEL}"; then
    echo "Model: ${V_BOARD_MODEL}"
fi

echo "System: ${V_SYSTEM}"
V_ARCH=$(uname -m)
echo "Architecture: ${V_ARCH}"
if [ "$V_BOARD" != "$V_ARCH" ]; then
    echo "Board: ${V_BOARD}"
fi

if echo "${V_BOARD}" | grep -qE "^rpi[0-9]$"; then
    REVISION=$(grep -E $'^Revision\t:' /proc/cpuinfo | head -1 | sed -e s+'^Revision\t: '++)
    test -n "${REVISION}" && echo "Revision: ${REVISION}"
fi

[[ -z ${V_CPUMODEL1} ]] || echo "CPU Model: ${V_CPUMODEL1}"

if test "${V_CPUMAXNB}" = "${V_CPUNB}"; then
    echo "CPU Cores: ${V_CPUNB}"
else
    echo "CPU Cores: ${V_CPUNB} / CPU Threads: ${V_CPUMAXNB}"
fi

if test "${V_CPUMINFREQ}" != "${V_CPUMAXFREQ}"; then
    echo "CPU Frequency: ${V_CPUMINFREQ}/${V_CPUMAXFREQ} MHz"
else
    echo "CPU Max Frequency: ${V_CPUMAXFREQ} MHz"
fi

declare -a check_cpu_features=("avx2" "sse4_1")
declare -a cpu_features=()
for feature in "${check_cpu_features[@]}"; do
    if grep -q " ${feature}" /proc/cpuinfo; then
        cpu_features+=("${feature}")
    fi
done

if [ "${#cpu_features[@]}" -gt 0 ]; then
    echo "CPU Features: ${cpu_features[@]}"
fi

# TDP
CPU_TDP=$(/usr/bin/batocera-settings-get system.cpu.tdp)
if ! [ -z "$CPU_TDP" ]; then
    MAX_TDP=$(/usr/bin/ryzenadj -i | awk '/PPT LIMIT FAST/ {printf "%.0f\n", $6}')
    echo "Ryzen Mobile TDP: ${MAX_TDP}W"
fi

# temperature
# Unit: millidegree Celsius
TEMPE=$(cat /sys/devices/virtual/thermal/thermal_zone*/temp /sys/class/hwmon/hwmon*/temp*_input 2>/dev/null | sort -rn | head -1 | sed -e s+"[0-9][0-9][0-9]$"++)
if test -n "${TEMPE}"; then
    echo "Temperature: ${TEMPE}°C"
fi

MEM_TOTAL_KB=$(head /proc/meminfo | grep -E "^MemTotal:" | sed -e s+"^MemTotal:[ ]*\([0-9]*\) kB$"+"\\1"+)
MEM_AVAILABLE_KB=$(head /proc/meminfo | grep -E "^MemAvailable:" | sed -e s+"^MemAvailable:[ ]*\([0-9]*\) kB$"+"\\1"+)
MEM_TOTAL_MB=$(expr "${MEM_TOTAL_KB}" / 1024)
MEM_AVAILABLE_MB=$(expr "${MEM_AVAILABLE_KB}" / 1024)
echo "Available Memory: ${MEM_AVAILABLE_MB}/${MEM_TOTAL_MB} MB"

# Get and display DISPLAY SERVER
DISPLAY_SERVER=$(batocera-resolution getDisplayMode)
if [ -n "$DISPLAY_SERVER" ]; then
    echo "Display Server: ${DISPLAY_SERVER}"
fi

# Get and display DISPLAY COMPOSITOR
DISPLAY_COMPOSITOR=$(batocera-resolution getDisplayComp)
if [ -n "$DISPLAY_COMPOSITOR" ]; then
    echo "Display Compositor: ${DISPLAY_COMPOSITOR}"
fi

# Current Resolution and Refresh Rate for single or multiple displays
OUTPUTS=$(batocera-resolution listOutputs)
set -- ${OUTPUTS}
NUM_OUTPUTS=$#

if [ "${NUM_OUTPUTS}" -le 1 ]; then
    echo "Display Output: ${OUTPUTS}"
    DISPLAYRES=$(batocera-resolution currentResolution)
    if [ ! -z "$WAYLAND_DISPLAY" ]; then # wayland
        DISPLAYRATE=$(batocera-resolution currentMode | awk -F'[x.]' '{printf "%.3f", $3 / 1000}')
    elif test -f /var/run/drmMode; then  # drm
        DISPLAYRATE=$(batocera-resolution currentMode | awk -F'\\.' '{print $4}')
    else # xorg
        DISPLAYRATE=$(batocera-resolution currentMode | awk -F'\\.' '{print $2"."$3}')
    fi
    echo "Display Resolution: ${DISPLAYRES}"
    echo "Display Refresh Rate: ${DISPLAYRATE}Hz"
else
    i=1
    for output in ${OUTPUTS}; do
        echo "Display Output ${i}: ${output}"     
        DISPLAYRES=$(batocera-resolution --screen "${output}" currentResolution)
        CURRENT_MODE=$(batocera-resolution --screen "${output}" currentMode)
        if [ ! -z "$WAYLAND_DISPLAY" ]; then # wayland
            DISPLAYRATE=$(echo "${CURRENT_MODE}" | awk -F'[x.]' '{printf "%.3f", $3 / 1000}')
        elif test -f /var/run/drmMode; then  # drm
            DISPLAYRATE=$(echo "${CURRENT_MODE}" | awk -F'\\.' '{print $4}')
        else # xorg
            DISPLAYRATE=$(echo "${CURRENT_MODE}" | awk -F'\\.' '{print $2"."$3}')
        fi
        echo "Display Resolution ${i}: ${DISPLAYRES}"
        echo "Display Refresh Rate ${i}: ${DISPLAYRATE}Hz"
        i=$((i + 1))
    done
fi

if [[ "${FULL_DISPLAY}" != 0 ]]; then
	# OPENGL
	if test "${V_BOARD}" = "x86" -o "${V_BOARD}" = "x86_64"; then
	    V_OPENGLVERSION=$(DISPLAY=$(getLocalXDisplay) glxinfo 2>/dev/null | grep -E '^OpenGL core profile version string:' | sed -e s+'^OpenGL core profile version string:[ ]*'++)
	    if test -z "${V_OPENGLVERSION}"; then
            V_OPENGLVERSION=$(DISPLAY=$(getLocalXDisplay) glxinfo 2>/dev/null | grep -E '^OpenGL version string:' | sed -e s+'^OpenGL version string:[ ]*'++)
	    fi
	    echo "OpenGL Driver Version: ${V_OPENGLVERSION}"
	fi

	# VULKAN
    if [ "$(batocera-vulkan hasVulkan)" = "true" ]; then
        if [ "$(batocera-vulkan hasDiscrete)" = "true" ]; then
            echo "Vulkan Driver Name: $(batocera-vulkan discreteName | tr -d '\n')"
            discreteIndex=$(batocera-vulkan discreteIndex)
            apiVersion=$(vulkaninfo | grep -A8 "GPU$discreteIndex" | awk '/apiVersion/ {print $3}')
            echo "Vulkan Driver Version: $apiVersion"
        else
            echo "Vulkan Driver Name: $(batocera-vulkan listDevices | tr -d '\n')"
            apiVersion=$(vulkaninfo | grep -A8 "GPU0" | awk '/apiVersion/ {print $3}')
            echo "Vulkan Driver Version: $apiVersion"
        fi
    fi
fi

# userdata type
INTERNALDEVICE=$(batocera-part "share")
INTERNALDEVICETYPE=$(blkid "${INTERNALDEVICE}" | sed -e s+'^.* TYPE="\([^"]*\)\".*'+'\1'+)
echo "Data Partition Format: ${INTERNALDEVICETYPE}"
echo "Data Partition Available Space: $(df -h ${INTERNALDEVICE} | awk '/\/userdata$/ {print $4}')"

PREFSRC=$(ip -j route get 1.1.1.1 2>/dev/null | jq -r '.[].prefsrc')
if [ -n "$PREFSRC" ]; then
    echo "Network IP Address: $PREFSRC"
else
    PREFSRC=$(ip -j route get 1:: 2>/dev/null | jq -r '.[].prefsrc')
    if [ -n "$PREFSRC" ]; then
        echo "Network IP Address: $PREFSRC"
    fi
fi

if [[ "${FULL_DISPLAY}" != 0 ]]; then
	MACADDR=$(ip a | grep -b1 "$PREFSRC" | awk '/link\/ether/ {print $3}' | sed 's/:/-/g')
	if [ -n "$MACADDR" ]; then
		echo "Corresponding MAC Address: $MACADDR"
	fi
fi

# Boot information
if [[ "${FULL_DISPLAY}" != 0 ]]; then
	if [ -d /sys/firmware/efi ]; then
		echo "UEFI Boot: Yes"
		if [ -x /usr/bin/mokutil ]; then
			echo "Secure Boot: $(mokutil --sb-state 2>&1 | sed 's/^SecureBoot validation is//' | paste -sd ';')"
		fi
	else
		echo "UEFI Boot: No"
	fi
fi

# battery
if test -n "${BATT}"; then
    echo "Battery: ${BATT}%"
fi

# battery health
design_energy_file="/sys/class/power_supply/BAT0/energy_full_design"
current_energy_file="/sys/class/power_supply/BAT0/energy_full"

if [ -e "$design_energy_file" ]; then
    design_energy=$(cat "$design_energy_file")
    current_energy=$(cat "$current_energy_file")
    
    battery_health=$(awk "BEGIN {
        health = ($current_energy / $design_energy) * 100;
        if (health > 100) 
            health = 100;
        printf \"%.0f\", health
    }")

    if [ ! -z "$battery_health" ]; then
        echo "Battery Health: $battery_health%"
    fi
fi

# PAD Battery
for PADBAT in /sys/class/power_supply/*/device/uevent
do
    if test -e "${PADBAT}"; then
        # HID devices only
        PADNAME=$(sed -nE 's/^HID_NAME=(.*)/\1/p' "${PADBAT}")
        if test -n "${PADNAME}"; then
            # Remove PID if it exists in the name
            PADNAME=$(echo "${PADNAME}" | sed -E 's/ PID:[0-9]+//')
            # parent of parent / uevent
            BATTUEVENT=$(dirname "${PADBAT}")
            BATTUEVENT=$(dirname "${BATTUEVENT}")/uevent
            BATT="$(batocera-padsinfo "${BATTUEVENT}")"
            echo "${PADNAME}: ${BATT}%"
        fi
    fi
done
